﻿/*
 * 由SharpDevelop创建。
 * 用户： 汪伟威
 * 日期: 2015/4/28
 * 时间: 14:19
 * 
 */
using System;
using NHibernate;
using FluentNHibernate.Cfg;
using System.Collections.Generic;

namespace NHibernateDemo
{
	/// <summary>
	/// Description of ProductDal.
	/// </summary>
	public class ProductDal
	{
		private ISessionFactory factory = NHibernateHelper.CreateSessionFactory();
		public ProductDal()
		{
			
		}

        public IList<Product> GetAll()
        {
            using (var session = factory.OpenSession())
            {
               return session.QueryOver<Product>().List();
            }
        }

        public Product GetById(int id)
        {
            using (var session = factory.OpenSession())
            {
                return session.Get<Product>(id);
            }
        }
		
		
		public void Create(Product item)
		{
            using (var session = factory.OpenSession())
            {
                session.Save(item);
                session.Flush();
            }
		}

        public void Update(Product item)
        { 
        	using (var session = factory.OpenSession())
    		using(var tx = session.BeginTransaction())
        	{
        		var product = session.Get<Product>(item.Id);
        		
        		product.Name = item.Name;
        		product.UnitPrice = item.UnitPrice;
        		product.Description = item.Description;
        		
        		tx.Commit();
        	}
        }

        public void Delete(int id)
        { 
        	using (var session = factory.OpenSession())
        	{
        		var product = session.Load<Product>(id);
        		session.Delete(product);
        		session.Flush();
        	}
        }
	}
}
